#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

using namespace ephemerals;

int sockfd = 0;
std::string server_ip;
uint16_t server_port;
pthread_t id;

void Recv()
{
    while(true)
    {
        //Bug：getline会阻塞，所以发送消息后才能收到消息，不合理。所以应该进行多线程处理，
        //一个线程负责发送消息，一个线程负责收消息

        //接收消息
        char buff[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int m = recvfrom(sockfd, buff, sizeof buff - 1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buff[m] = 0;
            std::cout << buff << std::endl;
        }
    }
}

void Send()
{
    //填写目标服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    std::string online = "上线了";
    sendto(sockfd, online.c_str(), online.size(), 0, (struct sockaddr*)&server, sizeof server);

    while(true)
    {
        //发送消息
        std::string input;
        std::getline(std::cin, input);
        
        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr*)&server, sizeof server);

        if(input == "QUIT")
        {
            pthread_cancel(id);
            break;
        }

        //扩展：input不仅可以包含消息内容，还可以包含消息类型、收发者等，
        //服务器可以进行报文解析从而实现更个性化的服务
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "ERROR:" << "Usage " << argv[0] << " port" << std::endl;
        exit(1);
    }

    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    //创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd == -1)
    {
        std::cerr << "socket error" << std::endl;
        exit(1);
    }

    //创建线程
    Thread recver(Recv);
    Thread sender(Send);

    recver.Start();
    sender.Start();

    id = recver.Id();

    recver.Join();
    sender.Join();
    return 0;
}